package com.jrui.www.t7manager.setting;

import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AlertDialog;
import android.text.Editable;
import android.text.InputType;
import android.text.TextWatcher;
import android.text.method.DigitsKeyListener;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.jrui.www.t7manager.BaseActivityWithManager;
import com.jrui.www.t7manager.CardSettingBean;
import com.jrui.www.t7manager.EnumEntry;
import com.jrui.www.t7manager.MainActivityCfg;
import com.jrui.www.t7manager.R;
import com.jrui.www.t7manager.SettingCardAdapter;
import com.jrui.www.t7manager.constant.T7Set;
import com.jrui.www.t7manager.util.T7Util;

import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class T7SettingActivity extends BaseActivityWithManager {
    private List<EnumEntry> enumEntries;
    private CardSettingBean setting;
    private SettingCardAdapter adapter;
    private ListView listView;
    private EditText editText;
    private int pMin;
    private int pMax;
    private CharSequence charCurrent;
    //    存放设置的值 用来和之后的值diff 是否需要向串口发送数据
    private String beforeValue;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        Intent intent = getIntent();
        String key = intent.getStringExtra("barName");
        this.setTitle(key);
        setContentView(R.layout.t7_setting);
//        根据key获取配置的list
        MainActivityCfg cfg = MainActivityCfg.getInstance();
        final List<CardSettingBean> settingList = cfg.getRouter().get(key);

        adapter = new SettingCardAdapter(T7SettingActivity.this,
                R.layout.setting_card, settingList);
        listView = (ListView) findViewById(R.id.t7_setting_list);
        listView.setAdapter(adapter);

        listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            int index = -1;

            @Override
            public void onItemClick(AdapterView<?> parent, View view,
                                    final int position, long id) {
                // 传递数据
                setting = settingList.get(position);
                // 数据为RW或者WO则可以打开dialog
                Boolean isHasDialog = null;
                isHasDialog = setting.getAccessMode().equals(T7Set.ACCESS_MODE_RO) ? false : true;
                if (isHasDialog) {
                    AlertDialog.Builder builder = new AlertDialog.Builder(T7SettingActivity.this);
                    builder.setTitle(setting.getDisplayName());
                    //当type为枚举时 则表现形式为单选列表
                    String type = setting.getType();

                    if (type.equals(T7Set.SETTING_TYPE_ENUMERATION)) {

                        //不使用adapter
                        enumEntries = setting.getEnumEntry();
                        List<String> keys = new ArrayList<>();
                        for (EnumEntry enumEntry : enumEntries) {
                            keys.add(enumEntry.getDisplayName());
                        }
                        String[] strings = new String[keys.size()];
                        keys.toArray(strings);
//                        枚举下拉框的默认选项应该结合value来判断
                        int currentIndex = T7Util.getCurrentIndex(setting);
                        builder.setSingleChoiceItems(strings, currentIndex, new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                index = which;
                            }
                        });
                        builder.setPositiveButton("取消", new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {

                            }
                        });
                        builder.setNegativeButton("设置", new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                if (index != -1) {
                                    String value = enumEntries.get(index).getValue();
                                    setting.setValue(value);
                                    updateItem(position);
                                }
                            }
                        });
                        builder.show();
                    }
//                    输入值为整数类型
                    else if (type.equals(T7Set.SETTING_TYPE_INTEGER)) {
                        LayoutInflater inflater = LayoutInflater.from(T7SettingActivity.this);
                        view = (LinearLayout) inflater.inflate(R.layout.input_with_title, null);
                        TextView textView = (TextView) view.findViewById(R.id.textView);
                        editText = (EditText) view.findViewById(R.id.editText);
                        textView.setText(setting.getDisplayName());
//                        edit 输入值的范围
                        String ranger = null;
                        String value = T7Util.getValue(setting);

                        if (value != null) {
                            beforeValue = value;
                            editText.setText(value);
                            charCurrent = value;
                        }
                        if (setting.getPMin() != null) {
                            pMin = Integer.parseInt(setting.getPMin().toString());
                            pMax = Integer.parseInt(setting.getPMax().toString());

                                ranger = new StringBuffer(setting.getPMin()).append(" ~ ").append(setting.getPMax()).toString();


                        }
                        editText.setHint(ranger);
                        editText.setKeyListener(DigitsKeyListener.getInstance("-1234567890"));
                        editText.addTextChangedListener(new TextWatcher() {
                            private CharSequence charBefore;

                            @Override
                            public void onTextChanged(CharSequence s, int start, int before, int count) {
                                //start 是当前光标的位置 s是当前正在输入的文本 还未渲染到页面上
                                if (s.length() > 1) {
                                    String regEx = "-";
                                    Pattern pattern = Pattern.compile(regEx);
                                    String result = s.subSequence(1, s.length()).toString();
                                    Matcher matcher = pattern.matcher(result);
                                    // 字符串是否与正则表达式相匹配
                                    boolean rs = matcher.find();
                                    if (rs) {
                                        Toast.makeText(getBaseContext(), "非法输入", Toast.LENGTH_SHORT).show();
                                        //恢复为之前输入的内容
                                        editText.setText(charBefore);
                                    }
                                }
                            }

                            @Override
                            public void beforeTextChanged(CharSequence s, int start, int count,
                                                          int after) {
                                charBefore = s.toString();
                            }

                            @Override
                            public void afterTextChanged(Editable s) {
                                if (s != null && !s.equals("")) {
                                    int markVal = 0;
                                    try {
                                        markVal = Integer.parseInt(s.toString());
                                    } catch (NumberFormatException e) {
                                        markVal = 0;
                                    }
                                    if (markVal > pMax) {
                                        Toast.makeText(getBaseContext(), "超出上限", Toast.LENGTH_SHORT).show();
                                        //setText不触发beforeTextChanged 会导致程序(onTextChanged方法)出错
                                        charBefore = String.valueOf(pMax);
                                        charCurrent = charBefore;
                                        editText.setText(String.valueOf(pMax));
                                        return;
                                    } else if (markVal < pMin) {
                                        Toast.makeText(getBaseContext(), "超出下限", Toast.LENGTH_SHORT).show();
                                        charBefore = String.valueOf(pMin);
                                        charCurrent = charBefore;
                                        editText.setText(String.valueOf(pMin));
                                        return;
                                    }
                                    //  这里有问题 上面还是需要return的
                                    charCurrent = s;
                                }
                            }
                        });
                        //校验输入框的输入类型和范围 需要抽象么
                        builder.setView(view);
                        builder.setPositiveButton("取消", new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {

                            }
                        });
                        builder.setNegativeButton("设置", new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                if (!charCurrent.equals(beforeValue)) {
                                    setting.setValue(charCurrent.toString());
                                    //  TODO 向串口发送数据
                                }
                            }
                        });
                        builder.show();
                    }

                }
            }
        });
    }

    private void updateItem(int position) {
        /**第一个可见的位置**/
        int firstVisiblePosition = listView.getFirstVisiblePosition();
        /**最后一个可见的位置**/
        int lastVisiblePosition = listView.getLastVisiblePosition();

        /**在看见范围内才更新，不可见的滑动后自动会调用getView方法更新**/
        if (position >= firstVisiblePosition && position <= lastVisiblePosition) {
            /**获取指定位置view对象**/
            View view = listView.getChildAt(position - firstVisiblePosition);
            adapter.getView(position, view, listView);
        }
    }


}
